import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getCurrentUser } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  
  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }
  
  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
  }
  
  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const res = await getCurrentUser()
      userInfo.value = res.data
      return res.data
    } catch (error) {
      // 如果是 401 或 403，说明 token 无效，清除本地数据
      if (error.response && (error.response.status === 401 || error.response.status === 403)) {
        logout()
      }
      console.error('获取用户信息失败：', error)
      return null
    }
  }
  
  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
  }
  
  return {
    userInfo,
    token,
    setToken,
    setUserInfo,
    fetchUserInfo,
    logout
  }
})

